<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

use mbilling\BillingBundle\Model\OrdersIpTableModel;
use mbilling\BillingBundle\Model\OrdersIpModel;
use mbilling\BillingBundle\Model\UsersAdminLogsModel;
use mbilling\BillingBundle\Entity\ordersIpTable;
use mbilling\BillingBundle\Entity\ordersIp;
use mbilling\BillingBundle\Entity\usersAdminLogs;

use mbilling\BillingBundle\Form\OrdersIpTableForm;

class OrdersIpTableController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $group_model = new OrdersIpTableModel($em);
        $ip_model = new OrdersIpModel($em);
        $groups = $group_model->findAll();
        $counts = array();
        foreach ($groups as $group)
        {
            $counts[$group->getId()] = array();
            $free_ips = $ip_model->findFree($group->getId());
            $notFree_ips = $ip_model->findNotFree($group->getId());
            
            array_push($counts[$group->getId()], count($free_ips));
            array_push($counts[$group->getId()], count($notFree_ips));
        }
        $error = $this->get('session')->get('synch_net_error');
        return $this->render('BillingBundle:Orders_ip_table:index.html.twig', array('groups' => $groups, 'counts' => $counts, 'error' => $error));
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $group_model = new OrdersIpTableModel($em);
        $ip_model = new OrdersIpModel($em);
        
        $group = new ordersIpTable();
        //$group_model->create($group->initDefaultEntity());//создание по умолчанию
        //return new RedirectResponse($this->generateUrl('orders_ip_show'));
        $form = $this->createForm(new OrdersIpTableForm, $group);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $temp = explode("/", $group->getIp());
                if (isset($temp['1']))
                {
                    $mask_dec = $temp['1'];
                    $temp_dec = $mask_dec;
                    $mask_dec_array = array();
                    $ip_dec_array = explode(".", $temp['0']);
                    for ($i = 0; $i < 4; $i++)
                    {
                        if ($temp_dec == 0)
                        {
                            $mask_dec_array[$i] = 0;
                        }
                        else if (($temp_dec - 8) >= 0)
                        {
                            $mask_dec_array[$i] = 8;
                            $temp_dec -= 8;
                        }
                        else if (($temp_dec - 8) < 0)
                        {
                            $mask_dec_array[$i] = $temp_dec;
                            $temp_dec = 0;
                        }
                    }
                    $mask_bin_array = array();
                    $invert_mask_bin_array = array();
                    $ip_bin_array = array();
                    for ($i = 0; $i < 4; $i++)
                    {
                        array_push($mask_bin_array, "");
                        for ($j = 0; $j < $mask_dec_array[$i]; $j++)
                        {
                            $mask_bin_array[$i] .= "1";
                        }
                        for ($j = $mask_dec_array[$i]; $j < 8; $j++)
                        {
                            $mask_bin_array[$i] .= "0";
                        }
                        $ip_bin_array[$i] = base_convert($ip_dec_array[$i], 10, 2);

                        $length = 8 - strlen($ip_bin_array[$i]);
                        for ($j = 0; $j < $length; $j++)
                        {
                            $ip_bin_array[$i] = "0".$ip_bin_array[$i];
                        }

                        $invert_mask_bin_array[$i] = bindec($mask_bin_array[$i]);
                        $invert_mask_bin_array[$i] = abs($invert_mask_bin_array[$i] - 255);
                        $invert_mask_bin_array[$i] = base_convert($invert_mask_bin_array[$i], 10, 2);
                        $length = 8 - strlen($invert_mask_bin_array[$i]);
                        for ($j = 0; $j < $length; $j++)
                        {
                            $invert_mask_bin_array[$i] = "0".$invert_mask_bin_array[$i];
                        }
                    }
                    $min_ip_bin_array = array();
                    $max_ip_bin_array = array();
                    $min_ip_dec_array = array();
                    $max_ip_dec_array = array();
                    for ($i = 0; $i < 4; $i++)
                    {
                        $min_ip_bin_array[$i] = $ip_bin_array[$i] & $mask_bin_array[$i];
                    }
                    $min_ip_bin_array['3'] |= "00000001";
                    for ($i = 0; $i < 4; $i++)
                    {
                        $min_ip_dec_array[$i] = bindec($min_ip_bin_array[$i]);
                    }

                    for ($i = 0; $i < 4; $i++)
                    {
                        $max_ip_bin_array[$i] = $ip_bin_array[$i] | $invert_mask_bin_array[$i];
                    }
                    $max_ip_bin_array['3'] = substr($max_ip_bin_array['3'], 0, 7);
                    $max_ip_bin_array['3'] .= "0";
                    for ($i = 0; $i < 4; $i++)
                    {
                        $max_ip_dec_array[$i] = bindec($max_ip_bin_array[$i]);
                    }

                    //print_r($min_ip_dec_array);
                    //print_r($max_ip_dec_array);

                    $group_model->create($form->getData());

                    $success_write = false;
                    //заменить на что нибудь рекурсивное
                    for ($i = $min_ip_dec_array['0']; $i <= $max_ip_dec_array['0']; $i++)
                    {
                        for ($j = $min_ip_dec_array['1']; $j <= $max_ip_dec_array['1']; $j++)
                        {
                            for ($k = $min_ip_dec_array['2']; $k <= $max_ip_dec_array['2']; $k++)
                            {
                                for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                                {
                                    $ip = $ip_model->findByIp($i.".".$j.".".$k.".".$l);
                                    if (!isset($ip))
                                    {
                                        $ip = new ordersIp();
                                        $ip->setIp($i.".".$j.".".$k.".".$l);
                                    }
                                    $ip->setIp($i.".".$j.".".$k.".".$l);
                                    $ip->setGroupId($group->getId());
                                    $ip->setTypeId('0');
                                    $ip->setIsActive('1');
                                    $ip_model->create($ip);
                                    $success_write = true;
                                }
                            }
                        }
                    }
                    if (!$success_write)
                        for ($j = $min_ip_dec_array['1']; $j <= $max_ip_dec_array['1']; $j++)
                        {
                            for ($k = $min_ip_dec_array['2']; $k <= $max_ip_dec_array['2']; $k++)
                            {
                                for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                                {
                                    $ip = $ip_model->findByIp($min_ip_dec_array['0'].".".$j.".".$k.".".$l);
                                    if (!isset($ip))
                                    {
                                        $ip = new ordersIp();
                                        $ip->setIp($min_ip_dec_array['0'].".".$j.".".$k.".".$l);
                                    }
                                    $ip->setGroupId($group->getId());
                                    $ip->setTypeId('0');
                                    $ip->setIsActive('1');
                                    $ip_model->create($ip);
                                    $success_write = true;
                                }
                            }
                        }
                    if (!$success_write)
                        for ($k = $min_ip_dec_array['2']; $k <= $max_ip_dec_array['2']; $k++)
                        {
                            for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                            {
                                $ip = $ip_model->findByIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$k.".".$l);
                                if (!isset($ip))
                                {
                                    $ip = new ordersIp();
                                    $ip->setIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$k.".".$l);
                                }
                                $ip->setGroupId($group->getId());
                                $ip->setTypeId('0');
                                $ip->setIsActive('1');
                                $ip_model->create($ip);
                                $success_write = true;
                            }
                        }
                    if (!$success_write)
                        for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                        {
                            $ip = $ip_model->findByIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$min_ip_dec_array['2'].".".$l);
                            if (!isset($ip))
                            {
                                $ip = new ordersIp();
                                $ip->setIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$min_ip_dec_array['2'].".".$l);
                            }
                            $ip->setGroupId($group->getId());
                            $ip->setTypeId('0');
                            $ip->setIsActive('1');
                            $ip_model->create($ip);
                            $success_write = true;
                        }
                }
                else
                {
                    $group_model->create($form->getData());

                    $ip = $ip_model->findByIp($temp['0']);
                    if (!isset($ip))
                    {
                        $ip = new ordersIp();
                        $ip->setIp($temp['0']);
                    }
                    $ip->setGroupId($group->getId());
                    $ip->setTypeId('0');
                    $ip->setIsActive('1');
                    $ip_model->create($ip);
                }
                $dns1 = $ip_model->findByIp($group->getDns1());
                if (!isset($dns1))
                {
                    $dns1 = new ordersIp();
                    $dns1->setIp($group->getDns1());
                }
                $dns1->setGroupId($group->getId());
                $dns1->setTypeId('1');
                $dns1->setAccount('system');
                $dns1->setIsActive('1');
                $ip_model->create($dns1);

                $dns2 = $ip_model->findByIp($group->getDns2());
                if (!isset($dns2))
                {
                    $dns2 = new ordersIp();
                    $dns2->setIp($group->getDns2());
                }
                $dns2->setGroupId($group->getId());
                $dns2->setTypeId('1');
                $dns2->setAccount('system');
                $dns2->setIsActive('1');
                $ip_model->create($dns2);

                $gateway = $ip_model->findByIp($group->getGateway());
                if (!isset($gateway))
                {
                    $gateway = new ordersIp();
                    $gateway->setIp($group->getGateway());
                }
                $gateway->setGroupId($group->getId());
                $gateway->setTypeId('1');
                $gateway->setAccount('system');
                $gateway->setIsActive('1');
                $ip_model->create($gateway);

                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('11');//страница список ip
                $log->setObjectId($group->getId());//изменяемый объект
                $log->setActionTypeId('1');//создание ip
                $log_model->create($log);
                
                $jabber = $this->get('jabber');
                $jabber->sendMessage(41, array('ip' => '"'.$group->getIp().'"'));

                return new RedirectResponse($this->generateUrl('orders_ip_table_show'));
            }
        }
        return $this->render('BillingBundle:Orders_ip_table:create.html.twig', array('form' => $form->createView()));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $group_model = new OrdersIpTableModel($em);
        
        $group = $group_model->findByPK($id);
        $source_ip = $group->getIp();
        $form = $this->createForm(new OrdersIpTableForm, $group);
        
        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $group_model->create($form->getData());
                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('11');//страница список ip table
                $log->setObjectId($group->getId());//изменяемый объект
                $log->setActionTypeId('2');//изменение ip table
                $log_model->create($log);

                $jabber = $this->get('jabber');
                $dest_ip = $form->getData()->getIp();
                $jabber->sendMessage(43, array('source_ip' => '"'.$source_ip.'"', 'dest_ip' => '"'.$dest_ip.'"'));
                
                return new RedirectResponse($this->generateUrl('orders_ip_table_show'));
            }
        }
        return $this->render('BillingBundle:Orders_ip_table:create.html.twig', array('form' => $form->createView()));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $group_model = new OrdersIpTableModel($em);
        $ip_model = new OrdersIpModel($em);

        $ips = $ip_model->findByGroupId($id);
        foreach ($ips as $ip)
        {
            $ip_model->removeByPK($ip->getId());
        }
        $group = $group_model->findByPK($id);
        $group_model->removeByPK($id);

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $log_model = new UsersAdminLogsModel($em);
        $log = new usersAdminLogs();
        $log->setAdminId($userCurrent->getId());
        $log->setPageId('11');//страница список ip table
        $log->setObjectId($id);//изменяемый объект
        $log->setActionTypeId('3');//удаление ip table
        $log_model->create($log);
        
        $jabber = $this->get('jabber');
        $jabber->sendMessage(42, array('ip' => '"'.$group->getIp().'"'));
                
        return new RedirectResponse($this->generateUrl('orders_ip_table_show'));
    }
    public function synchAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $group_model = new OrdersIpTableModel($em);
        $this->get('session')->set('synch_net_error', '');
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
        {
            $this->get('session')->set('synch_net_error', 'jabber error');
            return new RedirectResponse($this->generateUrl('orders_ip_table_show'));
        }
        
        $id = $jabber->sendMessage(36, array());
        $str = $jabber->waitMessage($id); 
        $groups = array();
        if (array_key_exists('error', $str))
        {
            $this->get('session')->set('synch_net_error', $str['error']);
            return new RedirectResponse($this->generateUrl('orders_ip_table_show'));
        }
        foreach($str as $s)
        {
            $pars = explode("\t", $s);
            if (!array_key_exists($pars['0'], $pars ))
            {
                $groups[$pars['0']] = $pars;
            }
        }
        $all_groups = $group_model->findAll();
        foreach($all_groups as $group)
        {
            $group_model->removeByPK($group->getId());
        }
        $all_ips = $ip_model->findAll();
        foreach($all_ips as $ip)
        {
            $ip_model->removeByPK($ip->getId());
        }
        foreach($groups as $pars)
        {
            $temp = explode("/", $pars['0']);
            if (isset($temp['1']))
            {
                $mask_dec = $temp['1'];
                $temp_dec = $mask_dec;
                $mask_dec_array = array();
                $ip_dec_array = explode(".", $temp['0']);
                for ($i = 0; $i < 4; $i++)
                {
                    if ($temp_dec == 0)
                    {
                        $mask_dec_array[$i] = 0;
                    }
                    else if (($temp_dec - 8) >= 0)
                    {
                        $mask_dec_array[$i] = 8;
                        $temp_dec -= 8;
                    }
                    else if (($temp_dec - 8) < 0)
                    {
                        $mask_dec_array[$i] = $temp_dec;
                        $temp_dec = 0;
                    }
                }
                $mask_bin_array = array();
                $invert_mask_bin_array = array();
                $ip_bin_array = array();
                for ($i = 0; $i < 4; $i++)
                {
                    array_push($mask_bin_array, "");
                    for ($j = 0; $j < $mask_dec_array[$i]; $j++)
                    {
                        $mask_bin_array[$i] .= "1";
                    }
                    for ($j = $mask_dec_array[$i]; $j < 8; $j++)
                    {
                        $mask_bin_array[$i] .= "0";
                    }
                    $ip_bin_array[$i] = base_convert($ip_dec_array[$i], 10, 2);

                    $length = 8 - strlen($ip_bin_array[$i]);
                    for ($j = 0; $j < $length; $j++)
                    {
                        $ip_bin_array[$i] = "0".$ip_bin_array[$i];
                    }

                    $invert_mask_bin_array[$i] = bindec($mask_bin_array[$i]);
                    $invert_mask_bin_array[$i] = abs($invert_mask_bin_array[$i] - 255);
                    $invert_mask_bin_array[$i] = base_convert($invert_mask_bin_array[$i], 10, 2);
                    $length = 8 - strlen($invert_mask_bin_array[$i]);
                    for ($j = 0; $j < $length; $j++)
                    {
                        $invert_mask_bin_array[$i] = "0".$invert_mask_bin_array[$i];
                    }
                }
                $min_ip_bin_array = array();
                $max_ip_bin_array = array();
                $min_ip_dec_array = array();
                $max_ip_dec_array = array();
                for ($i = 0; $i < 4; $i++)
                {
                    $min_ip_bin_array[$i] = $ip_bin_array[$i] & $mask_bin_array[$i];
                }
                $min_ip_bin_array['3'] |= "00000001";
                for ($i = 0; $i < 4; $i++)
                {
                    $min_ip_dec_array[$i] = bindec($min_ip_bin_array[$i]);
                }

                for ($i = 0; $i < 4; $i++)
                {
                    $max_ip_bin_array[$i] = $ip_bin_array[$i] | $invert_mask_bin_array[$i];
                }
                $max_ip_bin_array['3'] = substr($max_ip_bin_array['3'], 0, 7);
                $max_ip_bin_array['3'] .= "0";
                for ($i = 0; $i < 4; $i++)
                {
                    $max_ip_dec_array[$i] = bindec($max_ip_bin_array[$i]);
                }

                //print_r($min_ip_dec_array);
                //print_r($max_ip_dec_array);
                $group = new ordersIpTable();
                $group->setIp($temp['0'].'/'.$temp['1']);
                $group_model->create($group);

                $success_write = false;
                //заменить на что нибудь рекурсивное
                for ($i = $min_ip_dec_array['0']; $i <= $max_ip_dec_array['0']; $i++)
                {
                    for ($j = $min_ip_dec_array['1']; $j <= $max_ip_dec_array['1']; $j++)
                    {
                        for ($k = $min_ip_dec_array['2']; $k <= $max_ip_dec_array['2']; $k++)
                        {
                            for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                            {
                                $ip = $ip_model->findByIp($i.".".$j.".".$k.".".$l);
                                if (!isset($ip))
                                {
                                    $ip = new ordersIp();
                                    $ip->setIp($i.".".$j.".".$k.".".$l);
                                }
                                $ip->setIp($i.".".$j.".".$k.".".$l);
                                $ip->setGroupId($group->getId());
                                $ip->setTypeId('0');
                                $ip->setIsActive('1');
                                $ip_model->create($ip);
                                $success_write = true;
                            }
                        }
                    }
                }
                if (!$success_write)
                    for ($j = $min_ip_dec_array['1']; $j <= $max_ip_dec_array['1']; $j++)
                    {
                        for ($k = $min_ip_dec_array['2']; $k <= $max_ip_dec_array['2']; $k++)
                        {
                            for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                            {
                                $ip = $ip_model->findByIp($min_ip_dec_array['0'].".".$j.".".$k.".".$l);
                                if (!isset($ip))
                                {
                                    $ip = new ordersIp();
                                    $ip->setIp($min_ip_dec_array['0'].".".$j.".".$k.".".$l);
                                }
                                $ip->setGroupId($group->getId());
                                $ip->setTypeId('0');
                                $ip->setIsActive('1');
                                $ip_model->create($ip);
                                $success_write = true;
                            }
                        }
                    }
                if (!$success_write)
                    for ($k = $min_ip_dec_array['2']; $k <= $max_ip_dec_array['2']; $k++)
                    {
                        for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                        {
                            $ip = $ip_model->findByIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$k.".".$l);
                            if (!isset($ip))
                            {
                                $ip = new ordersIp();
                                $ip->setIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$k.".".$l);
                            }
                            $ip->setGroupId($group->getId());
                            $ip->setTypeId('0');
                            $ip->setIsActive('1');
                            $ip_model->create($ip);
                            $success_write = true;
                        }
                    }
                if (!$success_write)
                    for ($l = $min_ip_dec_array['3']; $l <= $max_ip_dec_array['3']; $l++)
                    {
                        $ip = $ip_model->findByIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$min_ip_dec_array['2'].".".$l);
                        if (!isset($ip))
                        {
                            $ip = new ordersIp();
                            $ip->setIp($min_ip_dec_array['0'].".".$min_ip_dec_array['1'].".".$min_ip_dec_array['2'].".".$l);
                        }
                        $ip->setGroupId($group->getId());
                        $ip->setTypeId('0');
                        $ip->setIsActive('1');
                        $ip_model->create($ip);
                        $success_write = true;
                    }
            }
            else
            {
                $group_model->create($form->getData());

                $ip = $ip_model->findByIp($temp['0']);
                if (!isset($ip))
                {
                    $ip = new ordersIp();
                    $ip->setIp($temp['0']);
                }
                $ip->setGroupId($group->getId());
                $ip->setTypeId('0');
                $ip->setIsActive('1');
                $ip_model->create($ip);
            }
        }
        return new RedirectResponse($this->generateUrl('orders_ip_table_show'));
    }
}